﻿using InDepth2Demo.Model;
using System;

namespace InDepth2Demo.Chapter4
{
    // 4.2.1
    internal class Null_DateTime_1
    {
        // 问题：在 C# 1 中，我想把我的 DateTime 变量设为null，但编译器不让，应该怎么办?

        public static void Call()
        {
            byte b = 0;
            byte c = 255;
            byte? d = null;
            if (!d.HasValue)
            {
                Console.WriteLine("这个 byte 没有值");
            }
            Console.WriteLine(DateTime.MinValue);

            // 两种都是一样的
            //Nullable<int> ni = 1;
            //int? ni2 = 1;

        }

        static void Call2()
        {
            //包装等于5 的值
            Nullable<int> x = 5;
            x = new Nullable<int>(5);
            Console.WriteLine("Instance with value:");
            Display(x);

            //输出：
            //Instance with value:
            //HasValue: True
            //Value: 5
            //Explicit conversion:5
            //GetValuerDefault():5
            //GetValue0rDefault(10):5
            //ToString():"5"
            //GetHashCode():5
        }

        static void Call3()
        {
            //构造没有值的实例
            Nullable<int> x = new Nullable<int>();
            Console.WriteLine("Instance without value:");
            Display(x);

            //输出：
            //Instance with value:
            //HasValue: False
            //GetValuerDefault():0
            //GetValue0rDefault(10):10
            //ToString():""
            //GetHashCode():0
        }

        static void Display(Nullable<int> x)
        {
            Console.WriteLine("HasValue: {0}", x.HasValue);

            if (x.HasValue)
            {
                Console.WriteLine("Value: {0}", x.Value);
                Console.WriteLine("Explicit conversion: {0}", (int)x);
            }

            Console.WriteLine("GetValueOrDefault(): {0}",
                              x.GetValueOrDefault());
            Console.WriteLine("GetValueOrDefault(10): {0}",
                              x.GetValueOrDefault(10));
            Console.WriteLine("ToString(): \"{0}\"", x.ToString());
            Console.WriteLine("GetHashCode(): {0}", x.GetHashCode());
            Console.WriteLine();
        }

        static void Display2(int x)
        {
            Console.WriteLine(x);
        }

        // 4.3.2 使用 null 进行复制比较
        public static void PersonDemo()
        {
            // 构造函数：public Person(string name, DateTime birth, DateTime? death)
            Person turing = new Person("Alan Turing ", new DateTime(1912, 6, 23), new DateTime(1954, 6, 7));
            Person knuth = new Person("Donald Knuth ", new DateTime(1938, 1, 10), null);
        }
    }
}
